<template>
  <div class='u-selectAttr'>
    <el-dialog
      title="选择预定义属性"
      :visible.sync="dialogVisible"
      :before-close="() => {this.dialogVisible = false}">
      <el-form>
        <!-- 属性列表 -->
        <el-form-item label='属性名称'>
          <el-select v-model='selectStatus' @change='selectedAttr'>
            <el-option
              v-for="(opt) in attrList"
              v-if="opt.isShow && !skuList.map(v => v.id).includes(opt.id)"
              :key="opt.id"
              :value="opt.id"
              :label="opt.name">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 输入类型 -->
        <el-form-item style='padding: 20px 0;' label='输入内容' v-if='selectStatusValueType === "1"'>
          <el-input v-model.trim='classContent' type='text' />
        </el-form-item>
        <!-- 选择分类 -->
        <el-form-item label='选择分类' v-else>
          <el-checkbox-group v-model="selectedCourseClassArray" @change='selectedCourseClass'>
            <el-checkbox v-for='(v) in courseClasslist' :disabled="v.disabled" :key='v.id' :label="v.id">{{ v.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- 二级分类 -->
        <!-- 如果分类列表有一个 isShowClass 是 true 且它有子级分类，才显示 -->
        <el-form-item label='二级分类' v-show='selectStatusValueType === "0" && courseClasslist.some(v => v.isShowClass && v.child.length)'>
          <div class='u-selectAttr-selectWrap'>
            <div v-for='v in courseClasslist' :key='v.id' class='item' v-if='v.isShowClass'>
              <p style="width: 80px;">{{v.name}}：</p>
              <el-select v-model="v.selects"  multiple placeholder="请选择">
                <el-option
                  v-for="(item) in v.child"
                  :disabled="item.disabled"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
        </el-form-item>
        <div class='btnWrap'>
          <el-button type='primary' @click='addSku(0)'>确定</el-button><el-button @click='dialogVisible = false'>取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
/**
 * 选择预定义分类模块
 * 点击选择属性按钮，显示当前模块
 * 注意！现在的功能，只有选择添加，编辑貌似被去掉了，暂不维护编辑功能
 * 只要选中了属性，就可以添加一个 sku
 */
import { setAttrData, createSkuById } from '@/util/formatAttr'

export default {

  name: 'SelectAttr',

  /**
   * @param {String} openType 打开的方式，add or edit
   * @param {Number} selectIndex 编辑时，点击的位置
   * @param {Array<object>} skuList sku 数组
   * @param {String} aType 获取属性的类型（商品、客户、订单等）
   */
  props: ['openType', 'selectIndex', 'skuList', 'aType'],

  data() {
    return {
      ifRequesting: false,
      dialogVisible: false,
      // 属性数组
      courseFeatureList: [],
      courseFeatureList_tmp: [],
      // 一级分类
      courseClasslist: [],
      // 二级分类
      courseClasslist2: [],
      // 选中的一级分类
      selectedCourseClassArray: [],
      // 选中的属性
      selectStatus: '',
      // 选中的属性类型
      selectStatusValueType: '',
      // 输入类型的分类内容
      classContent: '',
      attrList: []
    }
  },

  mounted() {
    // this.getAttributes()
    this.getAllAttrAndClass()
  },

  methods: {
    clearForm() {
      this.courseClasslist = []
      this.selectedCourseClassArray = []
      this.courseClasslist2 = []
      this.selectStatus = ''
      this.selectStatusValueType = ''
      this.classContent = ''
    },

    async getAllAttrAndClass() {
      const { code, data } = await this.$api.utilsGetAllClasses({
        aMerchantId: this.aFirmId, aType: this.aType
      })
      if (code === 0) {
        this.formatAttrAndClassData(data.list)
      }
    },

    /**
     * 组织 属性 -> 分类 -> 子级分类 的数据结构
     * 分类数据结构（一级） -> classes
     */
    formatAttrAndClassData(data) {
      data.forEach(v => {
        this.attrList.push(setAttrData(v))
      })
    },

    /**
     * 选择属性触发的回调
     * @param {String} 选中的属性 id
     */
    selectedAttr(id) {
      if (!id && id !== 0) return
      // 根据 id 获取选中的属性
      const obj = this.attrList.filter(v => v.id === id)[0]
      this.selectStatusValueType = obj.value_type
      // 输入类型就结束
      if (this.selectStatusValueType === '1') return false
      // 切换 class
      this.courseClasslist = obj.classes
    },

    /**
     * 选择一级分类触发的回调
     * @param {Array} classesId 选中的 classes id 位置数组
     */
    selectedCourseClass(classesId) {
      if (classesId.length === 0) {
        return false
      }
      this.courseClasslist.forEach((v) => {
        const isHaveSame = classesId.some(id => {
          if (v.id === id) {
            v.isShowClass = true
            return true
          }
        })
        if (!isHaveSame) {
          // 清空之前选中的
          v.selects = []
          v.isShowClass = false
        }
      })
    },

    /**
     * 添加新的 sku
     * 根据 List 文件定义好的 sku 数据结构生成对象
     */
    addSku(type) {
      // const openType = this.openType
      const selectIndex = this.selectIndex
      this.$emit('getSku',
        createSkuById(type, this.attrList, this.selectStatus, this.selectStatusValueType, this.classContent),
        this.openType === 'add' ? -1 : selectIndex)
      // 清空选中值
      this.selectStatus = ''
      this.selectStatusValueType = ''
      this.classContent = ''
      this.selectedCourseClassArray = []
      this.dialogVisible = false
      // 清空选择
      this.attrList.forEach(v => {
        v.selects = []
        v.classes.forEach(v2 => {
          v2.selects = []
          v2.isShowClass = false
        })
      })
    },

    async courseGetClasses() {
      const arr = []
      this.courseClasslist2.every(async v => {
        arr.push(new Promise(async resolve => {
          const data = await this.getClasses2(v.id, 'edit')
          v.list = data
          resolve()
        }))
      })
      return Promise.all(arr)
    },

    async editSku(obj) {
      this.selectStatus = obj.feature.value
      this.courseFeatureList = JSON.parse(JSON.stringify(this.courseFeatureList_tmp.map(v => v)))
      this.selectStatusValueType = this.courseFeatureList_tmp.filter(v => v.value === obj.feature.value)[0].value_type
      // 生成一级分类
      this.courseClasslist = []
      this.selectedCourseClassArray = []
      if (obj.feature.value_type === '1') {
        console.log(obj)
        this.classContent = obj.classes[0].name
        return
      }
      await this.getClasses(obj.feature.value, 'edit')
      this.courseClasslist.forEach((v, i) => {
        obj.classes.forEach(v2 => {
          if (v.id === v2.id) {
            this.selectedCourseClassArray.push(i)
          }
        })
      })
      this.courseClasslist2 = []
      // 生成二级分类
      console.log(obj)
      this.selectedCourseClassArray.forEach(v => {
        this.courseClasslist2.push({
          id: this.courseClasslist[v].id,
          name: this.courseClasslist[v].name,
          list: [],
          selects: []
        })
      })
      // 添加已选中的和获取列表
      await this.courseGetClasses()
      obj.classes2.forEach((v) => {
        this.courseClasslist2.forEach(async (item, i) => {
          if (v.parentId === item.id) {
            console.log(this.courseClasslist2[i].list)
            item.list.forEach((child, i) => {
              console.log(child.id, v.id)
              if (child.id === v.id) {
                item.selects.push(i)
              }
            })
          }
        })
      })
      console.log(this.courseClasslist2)
    },

    // 除去选中的属性
    deleteCheckedAttr() {
      this.courseFeatureList = JSON.parse(JSON.stringify(this.courseFeatureList_tmp.map(v => v)))
      this.skuList.forEach(sku => {
        this.courseFeatureList.some((v, i) => {
          if (v.value === sku.feature.value) {
            this.courseFeatureList.splice(i, 1)
            return true
          }
          return false
        })
      })
    },

    // 将已选的分类，添加 disabled
    addDisabledFromCheckedClass(data, type, edit) {
      console.log(edit, this.selectIndex)
      return data
      // if (this.skuList.length <= 0) return data
      // return data.map((v, i) => {
      //   this.skuList.forEach((sku, skuIndex) => {
      //     if (edit && skuIndex === this.selectIndex) return false
      //     sku[type].some(classes => {
      //       if (v.id === classes.id) {
      //         v.disabled = true
      //         return true
      //       }
      //       return false
      //     })
      //   })
      //   return v
      // })
    }
  }
}
</script>

<style lang='less' scoped>
.u-selectAttr {
  .el-form-item {
    padding-bottom: 20px;
    display: flex;
  }
  .btnWrap {
    display: flex;
    justify-content: flex-end;
  }
  &-selectWrap {
    overflow: hidden;
    .item {
      display: flex;
      padding-bottom: 10px;
      p {
        padding-right: 20px;
      }
    }
  }
}
</style>